package com.nic.view.util.download;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.nic.view.ViewConfig;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

/**
 * Created by Administrator on 2018/7/3.
 */

public class DownloadReceiver extends BroadcastReceiver {
    private static String TAG = "DownloadManager";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            installApk(context, id);
        } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            // DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            //获取所有下载任务Ids组
            //long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
            ////点击通知栏取消所有下载
            //manager.remove(ids);
            //Toast.makeText(context, "下载任务已取消", Toast.LENGTH_SHORT).show();
            //处理 如果还未完成下载，用户点击Notification ，跳转到下载中心
            Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(viewDownloadIntent);
        }
    }

    private static void installApk(Context context, long downloadApkId) {
        DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Intent install = new Intent(Intent.ACTION_VIEW);
        Uri downloadFileUri = dManager.getUriForDownloadedFile(downloadApkId);
        if (downloadFileUri != null) {

            Log.d(TAG, downloadFileUri.toString());
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //判断版本是否是 7.0 及 7.0 以上
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                try {
                    downloadFileUri = ViewConfig.getFileProviderA7(context, new File(new URI(downloadFileUri.toString())));
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                //设置 intent 目标应用类型和传递的数据，这句要放在查询之前
                install.setDataAndType(downloadFileUri,
                        "application/vnd.android.package-archive");
                //查询所有符合 intent 跳转目标应用类型的应用
                List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(install, PackageManager.MATCH_DEFAULT_ONLY);
                //然后全部授权
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, downloadFileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }

            } else {
                install.setDataAndType(downloadFileUri,
                        "application/vnd.android.package-archive");
            }
            context.startActivity(install);
        } else {
            Log.e(TAG, "download error");
        }
    }


    private static boolean isNeedDownload(Context mContext, long id, DownloadManager downloadManager) {

        boolean isNeedDownloadAgain = true;

        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor cursor = downloadManager.query(query);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int status = cursor.getInt(columnIndex);
            int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
            int reason = cursor.getInt(columnReason);

            switch (status) {
                case DownloadManager.STATUS_FAILED:
                    switch (reason) {
                        case DownloadManager.ERROR_CANNOT_RESUME:
                            //some possibly transient error occurred but we can't resume the download
                            break;
                        case DownloadManager.ERROR_DEVICE_NOT_FOUND:
                            //no external storage device was found. Typically, this is because the SD card is not mounted
                            break;
                        case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
                            //the requested destination file already exists (the download manager will not overwrite an existing file)
                            break;
                        case DownloadManager.ERROR_FILE_ERROR:
                            //a storage issue arises which doesn't fit under any other error code
                            break;
                        case DownloadManager.ERROR_HTTP_DATA_ERROR:
                            //an error receiving or processing data occurred at the HTTP level
                            break;
                        case DownloadManager.ERROR_INSUFFICIENT_SPACE://sd卡满了
                            //here was insufficient storage space. Typically, this is because the SD card is full
                            break;
                        case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
                            //there were too many redirects
                            break;
                        case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
                            //an HTTP code was received that download manager can't handle
                            break;
                        case DownloadManager.ERROR_UNKNOWN:
                            //he download has completed with an error that doesn't fit under any other error code
                            break;
                    }
                    isNeedDownloadAgain = true;
                    Log.i(TAG, "开始重新下载更新!");
                    break;
                case DownloadManager.STATUS_PAUSED:

                    switch (reason) {
                        case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
                            //the download exceeds a size limit for downloads over the mobile network and the download manager is waiting for a Wi-Fi connection to proceed

                            break;
                        case DownloadManager.PAUSED_UNKNOWN:
                            //the download is paused for some other reason
                            break;
                        case DownloadManager.PAUSED_WAITING_FOR_NETWORK:
                            //the download is waiting for network connectivity to proceed
                            break;
                        case DownloadManager.PAUSED_WAITING_TO_RETRY:
                            //the download is paused because some network error occurred and the download manager is waiting before retrying the request
                            break;
                    }
                    isNeedDownloadAgain = false;

                    Log.i(TAG, "下载已暂停，请继续下载！");
                    break;
                case DownloadManager.STATUS_PENDING:
                    //the download is waiting to start
                    isNeedDownloadAgain = false;
                    Log.i(TAG, "更新正在下载！");
                    break;
                case DownloadManager.STATUS_RUNNING:
                    //the download is currently running
                    isNeedDownloadAgain = false;
                    Log.i(TAG, "更新正在下载！");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //the download has successfully completed
                    isNeedDownloadAgain = false;
                    installApk(mContext, id);
                    break;
            }

        }
        return isNeedDownloadAgain;
    }
}
